Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news.kei.com!nntp.coast.net!howland.reston.ans.net!usc!news.cerf.net!nic.cerf.net!mpcline From: mpcline@nic.cerf.net (Marshall Cline) Newsgroups: comp.lang.c++ Subject: C++ FAQ: posting #1/4 [IGNORE EARLIER POSTING!] Followup-To: comp.lang.c++ Date: 26 Apr 1996 21:21:59 GMT Organization: Paradigm Shift, Inc (technology consulting) Lines: 1205 Sender: cline@parashift.com Distribution: world Expires: +1 month Message-ID: <4lrepn$33c@news.cerf.net> Reply-To: cline@parashift.com (Marshall Cline) NNTP-Posting-Host: nic.cerf.net Summary: Please read this before posting to comp.lang.c++ Archive-name: C++-faq/part1_4 [PLEASE NOTE: PLEASE IGNORE THE EARLIER POSTING OF THE FAQ (it had an error in the URL for the HTML version of the FAQ)]. BIG NEWS: * The content of this document has been extensively updated. * An HTML version that is broken up by sections is now available at: http://www.cerfnet.com/~mpcline/On-Line-C++-FAQs/ Posting 1 of 4. The On-Line C++ FAQs (Frequently Asked Questions) Revised Apr 26, 1996 ============================================================================== COMMON PREFIX INFORMATION: AUTHOR: Marshall P. Cline, Ph.D., cline@parashift.com Paradigm Shift, Inc. / One Park St. / Norwood, NY 13668 315-353-6100 (voice) / 315-353-6110 (fax) COPYRIGHT: This document (the "On-Line C++ FAQs") is Copyright (C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com. All rights reserved. Copying is permmitted only under designated situations (see section [1] for permissions). NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS. THE AUTHOR PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE. On-Line-C++-FAQs != C++-FAQs-Book: Note: This document (the "On-Line C++ FAQs") is not the same as the "C++ FAQs" book (e.g., the "C++ FAQs" book is five times larger than this on-line document). The "C++ FAQs" book is available in bookstores ("C++ FAQs" by Cline and Lomow, Addison-Wesley, 1995, ISBN 0-201-58958-3; see also http://heg-school.aw.com/cseng/authors/cline/FAQ/FAQ.html). ============================================================================== OVERVIEW OF ALL SECTIONS: 1. Copying permissions 2. On-line sites that distribute this document 3. "C++-FAQs-Book" versus "On-Line-C++-FAQs" 4. List of recent changes to this document 5. How to post to comp.lang.c++ (Read Before Posting!) 6. Managerial issues 7. Classes and objects 8. References 9. Inline functions 10. Constructors and destructors 11. Operator overloading 12. Friends 13. Input/output via and 14. Freestore management 15. Exceptions and error handling 16. Const correctness 17. Basics of inheritance 18. Inheritance and virtual functions 19. Inheritance and conformance 20. Inheritance and access rules 21. Inheritance and constructors/destructors 22. Private and protected inheritance 23. Abstraction 24. Style guidelines 25. Keys for Smalltalk programmers to learn C++ 26. Reference and value semantics 27. How to mix C and C++ 28. Pointers to member functions 29. Container classes and templates 30. Class libraries 31. Compiler dependencies 32. Miscellaneous technical issues 33. Miscellaneous environmental issues ============================================================================== SECTION [1]: Copying permissions [1.1] Can this document be copied legally? This document (the "On-Line C++ FAQs") is Copyright (C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com. All rights reserved. However you are allowed to copy and/or distribute all or part of this document under the following conditions: * No changes are made to whatever portions are copied and/or distributed. * And the "Author," "Copyright," "No Warranty," and "On-Line-C++-FAQs != C++-FAQs-Book" sections are retained verbatim and are displayed conspicuously. ============================================================================== [1.2] What if more and/or different privileges are wanted than those outlined above? If you need other permissions that aren't covered by the above, please contact the author. I'm a very reasonable man... ============================================================================== SECTION [2]: On-line sites that distribute this document [2.1] Where can I download this on-line document in the USA? http://www.cerfnet.com/~mpcline/On-Line-C++FAQs/ is the official home for this document. All others are mirror copies that may or may not be up to date. Also, http://www.connobj.com/cpp/cppfaq.htm has this document as one large HTML file (i.e., not broken up into sections). ============================================================================== [2.2] Where can I download this on-line document in Europe? * http://www.cs.bham.ac.uk/~jdm/CPP/cppfaq.html * http://www.informatik.uni-konstanz.de/~kuehl/cpp/cppfaq.htm * ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/ ============================================================================== [2.3] Where can I download a Chinese translation of this on-line document? ftp://ftp.cis.nctu.edu.tw/Documents/News/comp.lang.c++/c-cppfaq.* contains a Chinese translation encoded in the "Big5" code ("Big5" is a 16-bit Chinese code used mostly in Taiwan). ============================================================================== SECTION [3]: "C++-FAQs-Book" versus "On-Line-C++-FAQs" [3.1] Is there a "C++ FAQs" book I can buy in a bookstore? Yes. "C++ FAQs" by Cline and Lomow, Addison-Wesley, 1995, ISBN 0-201-58958-3. ============================================================================== [3.2] Is this on-line document the same as the "C++ FAQs" book? No! This document is called the "On-Line C++ FAQs" document. However the "On-Line C++ FAQs" document is not the same as the "C++ FAQs" book. The "C++ FAQs" book ("C++ FAQs", Addison-Wesley, 1995; http://heg-school.aw.com/cseng/authors/cline/FAQ/FAQ.html) is five (5) times larger than this on-line document. ============================================================================== [3.3] How can I download a free copy of the "C++ FAQs" book? sneaker-net://your.local.bookstore/tech-section/ISBN=0-201-58958-3 In other words, the "C++ FAQs" book is available in bookstores ("C++ FAQs", Addison-Wesley, 1995; ISBN 0-201-58958-3). It is not available in any on-line forum. Note that you can get a peek at some excerpts from the "C++ FAQs" book via http://heg-school.aw.com/cseng/authors/cline/FAQ/FAQ.html ============================================================================== [3.4] Why would I spend good money on a book when I can download it for free? Because the book contains five times more material than this on-line document. Many people have asked about the relationship between the book ("C++ FAQs", ISBN 0-201-58958-3) and this on-line document. Some have wondered whether the posting is equivalent to the book. The "C++ FAQs" book is loosely based on the same concepts as this on-line document. However the "C++ FAQs" book is approximately five (5) times bigger than this on-line document. For example, the book's discussions are much more detailed than in the on-line document, and the variety of FAQs is much wider in the book. The book also includes thousands of cross references, external references, and index terms, as well as many programming examples. ============================================================================== SECTION [4]: List of recent changes to this document [4.1] What updates were made for the 6/96 release? * Updated everything * Transformed the source from raw text to HTML * Reorganized, reworded, expanded, added examples, etc, etc ============================================================================== [4.2] What updates were made for the 5/96 release? * Added two more FAQs on including C header files (currently FAQ 112 & 113) * Updated the FAQ on pure virtual functions (near FAQ-77) * Updated the FAQ on delete this (near FAQ-39) ============================================================================== [4.3] What updates were made for the 4/96 release? * Added European mirror site for the WWW addresses: http://www.informatik.uni-konstanz.de/~kuehl/cpp/cppfaq.htm ============================================================================== [4.4] What updates were made for the 3/96 release? * Added a FAQ on whether C++ is better than Ada (or Visual Basic or ...) * Added WWW and anonymous ftp addresses: http://www.connobj.com/cpp/cppfaq.htm ftp://rtfm.mit.edu/pub/usenet-by-group/comp.lang.c++/ * Added a new FAQ on heterogeneous containers * Modified the FAQs covering coding standards * Added an Acronyms section for things like ARM, C++PL2, etc * Updated the dynamic-typing FAQs to reflect dynamic_cast and typeid() * Updated the ftp address for C++2LaTeX * Added a new LaTeX macro for pretty-printing the name "C++" * Added a paragraph in the FAQ on mixing new and free, or malloc and delete * Corrected an error in the on-line location for the ANSI-C++ draft standard * Corrected a access-level error in FAQ 45 * Added a note to FAQ 129 * Fixed the "iostream vs stdio" FAQ * Fixed a typo in FAQ 111 * Corrected numerous typographical errors ============================================================================== [4.5] What updates were made for the 1/96 release? * Anonymous ftp from soe.clarkson.edu still does not work * No significant changes were made this month ============================================================================== [4.6] What updates were made for the 9/95 release? * Added FAQ 41 on using a variable for the first dimension of a multi-dimensional array * Added FAQ 123 on the code from "Numerical Recipes" * Added section 20 ("Libraries"). It's still pretty sparse, but it's a start * Fixed a bug in FAQ 30 (there was no variable i) * Added FAQ 124 on dynamic linking to avoid bloated executables * Added FAQ 32 on trying to "reopen" cin and cout in binary mode * Added the access info to get the ANSI/ISO Committee Draft via ftp (FAQ 7) ============================================================================== [4.7] What updates were made for the 7/95 release? * Minor stuff (but not change in FTP access, below) ============================================================================== [4.8] What updates were made for the 6/95 release? * Corrected the mailing address where the ANSI-C++ Draft can be ordered * Added a FAQ on floating point [Thanks to Phil Staite] * Added a FAQ on multidimensional arrays [Thanks to Doug Shapter] * Added a FAQ on interrupt service routines and pointers to member functions * Reorganized the FAQ on allocating all objects of a certain class via new ============================================================================== [4.9] What updates were made for the 5/95 release? * Minor cosmetic changes ============================================================================== [4.10] What updates were made for the 4/95 release? * Added a question on a common BC++ Windows issue * Fixed the ftp address for NIHCL * Added an explanation that "ARM" is short for "Annotated Reference Manual" ============================================================================== [4.11] What updates were made for the 3/95 release? * Added a question on delete this * Added two questions on iostreams and eof * Fixed the entry on "c-mode" and "cc-mode" in Gnu emacs ============================================================================== [4.12] What updates were made for the 1/95 release? * A Chinese version of this document has been produced; details below ============================================================================== [4.13] What updates were made for the 12/94 release? * Added a FAQ on STL (currently #115) * Added a FAQ on name mangling (currently #119) * Fixed typo in FAQ that compared composition with private inheritance * Corrected some spelling errors ============================================================================== [4.14] What updates were made for the 11/94 release? * Added differentiator between "C++ FAQs" book and "On-Line C++ FAQs" * Other cosmetic changes ============================================================================== [4.15] What updates were made for the 10/94 release? * Fixed a few typos ============================================================================== [4.16] What updates were made for the 9/94 release? * Minor cosmetic changes ============================================================================== [4.17] What updates were made for the 8/94 release? * Made it up-to-date with respect to typeid and dynamic_cast * Made it up-to-date with respect to mutable and const_cast * Rewrote most of the answers to provide general cleanup * The quotation marks are now "..." rather than `...' or ``...'' * Sample code lines start with a tab; no other lines starts with a tab * Everything was edited; minor modifications everywhere ============================================================================== [4.18] What updates were made before 8/94? * This document was originally written in 1991 * I have no record of the specific changes that were made until 8/94 ============================================================================== SECTION [5]: How to post to comp.lang.c++ (Read Before Posting!) [5.1] How can I find out about general netiquette so I don't embarrass myself? General netiquette questions are answered in the newsgroup news.announce.newusers. This newsgroup contains many must-read articles for new users. Here are three important hints: * Some people post a question, then say something like, "Please respond by email because I don't normally read this newsgroup." This is really bad netiquette, and it almost guarantees that no one will answer your question (or worse: the only people who answer your question will be those who know so little about the way things work that they don't realize your bad form, and their answer will therefore probably be wrong). If you don't have enough time for the newsgroup, don't expect the newsgroup to have enough time for you! * It is bad netiquette to post a question to a newsgroup if that question is already answered in the newsgroup's FAQ. You really should read the FAQ before posting. If you don't, you're implicitly saying that your time is more valuable than the time of hundreds and hundreds of others. Tres uncool. Read the FAQ first! * There's something called "cross posting." This lets you post a question to a big pile of newsgroups at once. Don't! Cross posting to a large collection of newsgroups is bad netiquette. You will get flamed. Instead you should post to the newsgroup (singular) that best fits your question (see next FAQ for how to select the "best" newsgroup). If you don't get an answer in the "right" newsgroup and feel you must post somewhere else, at least consider redirecting followups back to the appropriate newsgroup. ============================================================================== [5.2] Which newsgroup should I post my questions? Here's a list of some very active newsgroups, along with some sample topics that should give you an idea of the topics discussed there: * comp.lang.c++ * The main topic of comp.lang.c++ is supposed to be the C++ language itself * Examples: C++ code design, syntax, style * If you want to post a question regarding a particular operating system (e.g., Windows 3.x, Windows 95, UNIX, etc), please post it in an operating-system-specific newsgroup; do not post it in comp.lang.c++ * comp.lang.c++.moderated * A moderated variant of comp.lang.c++ * The moderator's job is to keep the signal-to-noise ratio higher than in comp.lang.c++ * comp.object * Mostly OO design issues, with less emphasis on OO programming) * That group's FAQ contains an excellent introduction to OO along with an overview of OO terms and concepts * comp.std.c++ * Discussion directly related to the evolving ANSI/ISO C++ standard * The evolving ANSI/ISO C++ standard is discussed below * comp.os.ms-windows.programmer.tools * This group is intended for discussions about the selection and use of tools for Windows software development * comp.os.ms-windows.programmer.misc * This group is for all other discussions about Windows software development * There's one FAQ list for all the comp.os.ms-windows.programmer.* groups * Sample topic: Accessing C++ classes in a DLL * Sample topic: A dialog as an MDI child window [with OWL] * Sample topic: Disabled menu choices become enabled [with MFC] * Sample topic: Using STRICT with windows.h * Sample topic: A programmer's bibliography * comp.os.msdos.programmer * Much of the traffic is about language products, chiefly from Borland and Microsoft * Note: The FAQ for this group is not available at rtfm.mit.edu; it is at ftp://oak.oakland.edu/pub/msdos/info and ftp://garbo.uwasa.fi/pc/doc-net * Sample topic: How can I read a character without [waiting for] the Enter key? * Sample topic: How can I read, create, change, or delete the volume label? * Sample topic: How do I configure a COM port and use it to transmit data? * Sample topic: How can a C program send control codes to my printer? * Sample topic: How can I find the Microsoft mouse position and button status? * Sample topic: How can I write a TSR (terminate-stay-resident) utility? * Sample topic: How can I contact [Borland, Microsoft]? * comp.os.msdos.programmer.turbovision * Borland's character-mode framework * omp.unix.programmer * Sample topic: How do I use popen() to open a process for reading and writing? * Sample topic: How do I sleep() in a C program for less than one second? * comp.unix.solaris * Covers SunOS 4.x and Solaris * Sample topic: Signal Primer * Sample topic: Waiting for Children to Exit * gnu.g++.help * Sample topic: Where can I find a demangler? * Sample topic: Getting gcc/g++ binaries for Solaris 2.x * Sample topic: What documentation exists for g++ 2.x? * gnu.g++.bug * Bug reports for g++; see the g++ docs * comp.lang.c * FAQ is posted monthly, and is maintained by Steve Summit, scs@eskimo.com * Sample topic: I'm confused. NULL is guaranteed to be 0, but the null pointer is not? * Sample topic: So what is meant by the "equivalence of pointers and arrays" in C? * Sample topic: Why doesn't printf("%d\n", i++ * i++); work? * Sample topic: How can I write a function that takes a variable number of arguments? [stdarg.h or varargs.h] * Sample topic: How do I declare an array of pointers to functions returning pointers to functions returning pointers to characters? * comp.graphics * Issues revolving around graphics programming * comp.sources.wanted * If you want some source code for something, post your request there * comp.programming * General programming issues ============================================================================== [5.3] How do I get the FAQs for a particular newsgroup? Let me count the ways... FAQs (Frequently Asked Questions lists) are available 24-hours a day via: * ftp or WWW: ftp://rtfm.mit.edu/pub/usenet/ * e-mail: send a message with the line "help" to mail-server@rtfm.mit.edu * usenet: many FAQs are available in the newsgroup news.answers Please, PLEASE do not send email to me! ============================================================================== [5.4] How do I post a question about code that doesn't work correctly? Here's some guidelines you should follow that will help people reading comp.lang.c++ help you with an answer to your programming problem. 1. Please read the previous FAQ to make sure that your question is about the C++ language and not a question about programming on your system (e.g., graphics, printers, devices, etc.) or using your compilation environment (e.g., "the IDE crashes when I...," "how do you turn off warnings about...," "how do I tell it to link my libraries"). If you want to know why your virtual CmOk() function isn't being called in your OWL program, your question is probably more appropriate in the Windows programming newsgroup. If you can write a small stand-alone program which exhibits the same undesired compiler error or behavior as your OWL program, by all means post here in comp.lang.c++ since C++ programmers using other systems could be of help. 2. Be descriptive in the subject line. "C++ problem" leaves a lot to the imagination. "Problem new'ing a multi-dimensional array" is good. Refrain from exclamation points, cries for HELPPP, and the once funny "SEX SEX SEX." If you think the problem is specific to your compiler, you might want to mention the compiler/version in the subject line. 3. Post code that is complete and compilable. It's extremely difficult to debug or reconstruct a program from a human language description. By "complete code" I mean that any types and functions used are declared, headers are #include'd, etc. Please strip the code down to the bare essentials. We don't need a program that does something useful at run-time, or even links. We just need to be able to reproduce the undesired compiler error (possibly on a different compiler). By "compilable code" I mean that it doesn't contain a bunch of uncommented ellipses or line numbers at the beginning of each line: 14: #include 15: class Foo { ... }; // This is annoying Try to organize the code into one linear program instead of making us cut out and create header files. Be very careful if you are typing the code into your article -- it's often difficult to tell whether something is a typo or the real cause of the problem. Try using your editor's cut and paste or "insert file" feature instead. 4. Mention what compiler, compiler version, and system you're using. I know, I just said that system-specific questions should go to a system-specific newsgroup, but compiler information is often very useful in diagnosing the problem: ("yeah, I remember Acme 1.2 having lots of problems in this area"). It also warns other users of that compiler about possible bugs. 5. Show us the exact compiler and linker options and libraries you used when building your program. 6. List the exact error message and where the error was given. "Virtual functions don't work" doesn't tell us whether its a compile-, link-, or run-time problem. If the problem is at run-time, give a good description of the behavior and any relevant information about your system setup. 7. Include a working e-mail address in your signature. If the address in given your article's "From:" line is not correct, please notify your system administrator. Until it is fixed, add a "Reply-To:" line to your headers that uses your correct e-mail address. 8. Please read the rest of this FAQ -- chances are your problem, or a closely related problem, is discussed here. Thank you and I hope these suggestions help you find a solution to your problem. ============================================================================== SECTION [6]: Managerial issues [6.1] What is OO? What is C++? Object-oriented techniques are the best way we know of to develop large, complex software applications and systems. C++ is an OO programming language. C++ can also be used as a traditional programming language (as "as a better C"). However if you use it "as a better C," don't expect to get the benefits of object-oriented programming. OO hype: the software industry is "failing" to meet demands for large, complex software systems. But this "failure" is actually due to our successes: our successes have propelled users to ask for more. Unfortunately we created a market hunger that the "structured" analysis, design and programming techniques couldn't satisfy. This required us to create a better paradigm. ============================================================================== [6.2] Is C++ better than Ada? (or Pascal, C, FORTRAN, Visual Basic, or any other language?) This question generates much much more heat than light. Please read the following before posting some variant of this question. In 99% of the cases, programming language selection is dominated by business considerations, not by technical considerations. Things that really end up mattering are things like availability of a programming environment for the development machine, availability of runtime environment(s) for the deployment machine(s), licensing/legal issues of the runtime and/or development environments, availability of trained developers, availability of consulting services, and corporate culture/politics. These business considerations generally play a much greater role than compile time performance, runtime performance, static vs. dynamic typing, static vs. dynamic binding, etc. Therefore anyone who argues in favor of one language over another in a purely technical manner (i.e., who ignores the dominant business issues) exposes themselves as a techie weenie, and deserves not to be heard. ============================================================================== [6.3] What are some features of C++? * Growth of C++: C++ is by far the most popular OO programming language. The number of C++ users is doubling at least once every year. If you're a manager, this means you will very likely have a wide selection of development tools, environments, and consulting services. If you're a programmer, this means that knowing C++ is an essential resume-stuffer (but you need to think in OO to make yourself really valuable; tons and tons and tons of people simply know the syntax of C++, but they think of it as a souped up C; those people need to learn OO). * Encapsulation: Hiding stuff allows you to change one chunk of a system without breaking other chunks. The chunks (called "classes" in OO-speak) are given safe interfaces. Users of a chunk use its interface only. The relatively volatile "implementation" of this interface is "encapsulated" ("put into a capsule") to prevent users from becoming reliant on the temporary, fickle decisions of the class builder. In C, this was done by making things static in a module, which prevented another module from accessing the static stuff. * Multiple instances: The typical C solution to encapsulation (see above) doesn't support multiple instances of the data (C doesn't directly support the tricks needed to make multiple instances of a module's static data). If multiple instances were needed in C, programmers typically used a struct. But unfortunately C structs don't support encapsulation). In C++, programmers can have both multiple instances and encapsulation via a class: the public part of a class contains the class's interface (normally these are a special kind of function called a "member function"), and the private part of a class contains the class's implementation (typically these are where the bits live). * Inline function calls: In straight C, you can achieve "encapsulated structs" by putting a void* in a struct, in which case the void* points to the real data, but users of the struct don't know how to interpret the stuff pointed to by the void*, which gave a form of encapsulation (obviously the access functions used pointer casts). This forfeits type safety, and also imposes a function call to access even trivial fields of the struct (if you allowed direct access to the struct's fields, the underlying data structure would be difficult to change since then anyone and everyone would be able to get direct access; i.e., they would know how to interpret the stuff pointed to by the void*). Function call overhead is small, but can add up. C++ classes allow function calls to be expanded inline, so you have: the (1) safety of encapsulation, (2) convenience of multiple instances, (3) speed of direct access. Furthermore the parameter types of these inline functions are checked by the compiler, an improvement over C's #define macros. * Overloading operators: C++ lets you overload the standard operators on a class, which lets users exploit their intuition (e.g., myString + yourString might do string concatenation, myDate++ might increment the date, z1 * z2 might multiply complex numbers z1 and z2, a[i] might access the i'th element of the "linked list" called a, etc). You can even have "smart pointers" that could "point" to a disk record or wherever (x = *p could "dereference" such a pointer, which could seek to the location on disk where p "points" and return the record). This allows users to program in the language of the problem domain rather than in the language of the machine. * Inheritance: We still have just scratched the surface. In fact, we haven't even gotten to the "object-oriented" part yet! Suppose you have a Stack data type with operations push(), pop(), etc. Suppose you want an InvertableStack, which is "just like" Stack except it also has an invert() operation. In C style, you'd have to either (1) modify the existing Stack module (trouble if Stack is being used by others), or (2) copy Stack into another file and text edit that file (results in lots of code duplication, another chance to break something tricky in the Stack part of InvertableStack, and twice as much code to maintain). C++ provides a much cleaner solution: inheritance. InvertableStack inherits everything from Stack, and InvertableStack adds the invert() operation. Done. Stack itself remains "closed" (untouched, unmodified), and InvertableStack doesn't duplicate the code for push(), pop(), etc. * Polymorphism and dynamic binding: The real power of OO isn't just inheritance, but is the ability to pass an InvertableStack around as if it actually were a Stack. This is "safe" since (in C++ at least) the is-a relation follows public inheritance (i.e., a InvertableStack is-a Stack that can also invert() itself). Polymorphism and dynamic binding are easiest to understand from an example, so here's a "classic": a graphical drawing package might deal with Circles, Squares, Rectangles, general Polygons, and Lines. All of these are Shapes. Most of the draw package's functions need a Shape parameter (as opposed to some particular kind of shape like Square). E.g., a pick_and_drag(Shape*) function might be called if a Shape is picked by a mouse, and the function might cause the Shape to get dragged across the screen and placed into a new location. Polymorphism and dynamic binding allow the code to work correctly even if the compiler knows only that the parameter is a Shape without knowing the exact kind of Shape it is. Furthermore suppose such a pick_and_drag(Shape*) function was compiled on Tuesday, and on Wednesday you decide to add the Hexagon shape. Strange as it sounds, pick_and_drag() will still work with a Hexagon, even though the Hexagon code didn't even exist when pick_and_drag() was compiled!! (it's not really "amazing" once you understand how the C++ compiler does it -- but it's still very convenient!) ============================================================================== [6.4] Who uses C++? Lots and lots of companies and government sites. Lots. Statistically, 5 people became new C++ programmers while you read the words of the previous FAQ. ============================================================================== [6.5] Are there any C++ standardization efforts underway? Yes; ANSI (American) and ISO (International) groups are working closely with each other. The ANSI-C++ committee is called "X3J16". The ISO C++ standards group is called "WG21". The major players in the ANSI/ISO C++ standards process includes just about everyone: AT&T, IBM, DEC, HP, Sun, MS, Borland, Zortech, Apple, OSF, etc ad nauseum. Dozens of people attend each meeting. People come from USA, UK, Japan, Germany, Sweden, Denmark, France, ... (all have "local" committees sending official representatives and conducting "local" meetings). ============================================================================== [6.6] Where can I get a copy of the latest ANSI/ISO-C++ draft standard? The ISO Committee Draft for C++ and the ANSI C++ Draft (the document that is going out for public review) is available from: * http://www.cygnus.com/~mrs/wp-draft You can also get Postscript and Adobe Acrobat versions from: * ftp://research.att.com/dist/c++std/WP * ftp://ftp.maths.warwick.ac.uk:/pub/c++/std/WP * ftp://ftpt.su.edu.au:/pub/C++/CommitteeDraft You can get HTML and ASCII versions: * ftp://ftp.cygnus.com/pub/g++ You can also get a paper copy from: * Lynn Barra * Ask for the latest version of "Draft Proposed American National Standard for Information Systems -- Programming Language C++" which is document number CD14882 * It is typically shipped 2-day FedEx within the continental US You can also order a paper copy via snail-mail: * X3 Secretariat 1250 Eye Street NW Suite 200 Washington, DC 20005 202-626-5738 * Ask for the latest version of "Draft Proposed American National Standard for Information Systems -- Programming Language C++" which is document number CD14882 * It is typically shipped 2-day FedEx within the continental US ============================================================================== [6.7] Is C++ backward compatible with ANSI-C? Almost. C++ is as close as possible to compatible with C, but no closer. In practice, the major difference is that C++ requires prototypes, and that f() declares a function that takes no parameters (in C, f() is the same as f(...)). There are some very subtle differences as well, like sizeof('x') is equal to sizeof(char) in C++ but is equal to sizeof(int) in C. Also, C++ puts structure "tags" in the same namespace as other names, whereas C requires an explicit struct (e.g., the typedef struct Fred Fred; technique still works, but is redundant in C++). ============================================================================== [6.8] How long does it take to learn C++? Companies like Paradigm Shift, Inc. (info@parashift.com) successfully teach standard industry "short courses," where we compress a university semester course into one 40 hour work week. But regardless of where you get your training, make sure the courses have a hands-on element, since most people learn best when they have projects to help the concepts "gel." It takes 6-12 months to become proficient in OO/C++. Less if the developers have easy access to a "local" body of experts, more if there isn't a "good" general purpose C++ class library available. To become one of these experts who can mentor others takes around 3 years. Some people never make it. You don't have a chance unless you are teachable and have personal drive. As a bare minimum on "teachability," you have to be able to admit when you've are wrong. As a bare minimum on "drive," you must be willing to put in some extra hours (it's a lot easier to learn some new facts than it is to change your paradigm [i.e., to change the way you think; to change your notion of goodness; to change your mental model of the world of technology]). ============================================================================== SECTION [7]: Classes and objects [7.1] What is a class? The fundamental building block of OO software. A class defines a data type, much like a struct would be in C. In a computer science sense, a type consists of both a set of states and a set of operations which transition between those states. Thus int is a type because it has both a set of states and it has operations like i + j or i++, etc. In exactly the same way, a class provides a set of (usually public) operations, and a set of (usually non-public) data bits representing the abstract values that instances of the type can have. Think of int as a class that has member functions called operator++, etc. Note: a C programmer can think of a class as a C struct whose members default to private. But if that's all you think of a class, then you probably need to experience a personal paradigm shift. ============================================================================== [7.2] What is an object? A region of storage with associated semantics. After the declaration int i; we say that "i is an object of type int." In OO/C++, "object" usually means "an instance of a class." Thus a class defines the behavior of possibly many objects (instances). ============================================================================== SECTION [8]: References [8.1] What is a reference? An alias (an alternate name) for an object. References are frequently used for pass-by-reference: void swap(int& i, int& j) { int tmp = i; i = j; j = tmp; } main() { int x, y; // ... swap(x,y); } Here i and j are aliases for main's x and y respectively. In other words, i is x -- not a pointer to x, nor a copy of x, but x itself. Anything you do to i gets done to x, and vice versa. OK. That's how you should think of references as a programmer. Now, at the risk of confusing you by giving you a different perspective, here's how references are implemented. Underneath it all, a reference i to object x is typically the machine address of the object x. But when the programmer says i++, the compiler generates code that increments x. In particular, the address bits that the compiler uses to find x are not changed. A C programmer will think of this as if you used the C style pass-by-pointer, with the syntactic variant of (1) moving the & from the caller into the callee, and (2) eliminating the *s. In other words, a C programmer will think of i as a macro for (*p), where p is a pointer to x (e.g., the compiler automatically dereferences the underlying pointer; i++ is changed to (*p)++; i = 7 is automatically changed to *p = 7). Important note: Even though a reference is often implemented using an address in the underlying assembly language, please do not think of a reference as a funny looking pointer to an object. A reference is the object. It is not a pointer to the object, nor a copy of the object. It is the object. ============================================================================== [8.2] What happens if you assign to a reference? You change the referent (the object to which the reference refers). Remember: the reference is the referent, so changing the reference changes the referent. In compiler writer lingo, a reference is an "lvalue" (something that can appear on the left hand side of an assignment operator). ============================================================================== [8.3] What happens if you return a reference? The function call can appear on the left hand side of an assignment operator. This ability may seem strange at first. For example, no one thinks the expression f() = 7 makes sense. Yet, if a is an object of class Array, most people think that a[i] = 7 makes sense even though a[i] is really just a function call in disguise (it calls Array::operator[](int), which is the subscript operator for class Array). class Array { public: int size() const; float& operator[] (int index); // ... }; main() { Array a; for (int i = 0; i < a.size(); ++i) a[i] = 7; // This line invokes Array::operator[](int) } ============================================================================== [8.4] How can you reseat a reference to make it refer to a different object? No way. You can't separate the reference from the referent. Unlike a pointer, once a reference is bound to an object, it can not be "reseated" to another object. The reference itself isn't an object (it has no identity; taking the address of a reference gives you the address of the referent; remember: the reference is its referent). ============================================================================== [8.5] When should I use references, and when should I use pointers? Use references when you can, and pointers when you have to. References are usually preferred over pointers whenever you don't need "reseating" (see previous FAQ). This usually means that references are most useful in a class's public interface. References typically appear on the skin of an object, and pointers on the inside. The exception to the above is where a function's parameter or return value needs a "sentinel" reference. This is usually best done by returning/taking a pointer, and giving the NULL pointer this special significance (references should always alias objects, not a dereferenced NULL pointer). Note: Old line C programmers sometimes don't like references since they provide reference semantics that isn't explicit in the caller's code. After some C++ experience, however, one quickly realizes this is a form of information hiding, which is an asset rather than a liability. E.g., programmers should write code in the language of the problem rather than the language of the machine. ============================================================================== SECTION [9]: Inline functions [9.1] What's the deal with inline functions? An inline function is a function whose code gets inserted into the caller's code stream. Like a #define macro, inline functions improve performance by avoiding the overhead of the call itself and (especially!) by the compiler being able to optimize through the call ("procedural integration"). ============================================================================== [9.2] How do you tell the compiler to make a non-member function inline? When you declare an inline function, it looks just like a normal function: void f(int i, char c); But when you define an inline function, you prepend the function's definition with the keyword inline, and you put the definition into a header file: inline void f(int i, char c) { // ... } Note: It's usually imperative that the function's definition (the part between the {...}) be placed in a header file. If you put the inline function's definition into a .cpp file, and if it is called from some other .cpp file, you'll get an "unresolved external" error from the linker. ============================================================================== [9.3] How do you tell the compiler to make a member function inline? When you declare an inline member function, it looks just like a normal member function: class Fred { public: void f(int i, char c); }; But when you define an inline member function, you prepend the member function's definition with the keyword inline, and you put the definition into a header file: inline void Fred::f(int i, char c) { // ... } It's usually imperative that the function's definition (the part between the {...}) be placed in a header file. If you put the inline function's definition into a .cpp file, and if it is called from some other .cpp file, you'll get an "unresolved external" error from the linker. ============================================================================== [9.4] Is there another way to tell the compiler to make a member function inline? Yep: define the member function in the class body itself: class Fred { public: void f(int i, char c) { // ... } }; Although this is easier on the person who writes the class, it's harder on all the readers since it mixes "what" a class does with "how" it does them. Because of this mixture, we normally prefer to define member functions outside the class body with the inline keyword (see previous FAQ). The insight that makes sense of this: in a reuse-oriented world, there will usually be many people who use your class, but there is only one person who builds it (yourself); therefore you should do things that favor the many rather than the few. ============================================================================== [9.5] Why should I use inline functions? Why not just use plain old #define macros? Because #define macros are evil. Unlike #define macros, inline functions avoid infamous macro errors since inline functions always evaluate every argument exactly once. In other words, invoking an inline function is semantically just like invoking a regular function, only faster: // A macro that returns the absolute value of i #define unsafe(i) \ ( (i) >= 0 ? (i) : -(i) ) // An inline function that returns the absolute value of i inline int safe(int i) { return i >= 0 ? i : -i; } int f(); void userCode(int x) { int ans; ans = unsafe(x++); // Error! x is incremented twice ans = unsafe(f()); // Danger! f() is called twice ans = safe(x++); // Correct! x is incremented once ans = safe(f()); // Correct! f() is called once } Also unlike macros, argument types are checked, and necessary conversions are performed correctly. Macros are bad for your health; don't use them unless you have to. ============================================================================== [9.6] Are inline functions guaranteed make your performance better? Nope. Beware that overuse of inline functions can cause code bloat, which can in turn have a negative performance impact in paging environments. ============================================================================== SECTION [10]: Constructors and destructors [10.1] What's the deal with constructors? Constructors build objects from dust. Constructors are like "init functions". They turn a pile of arbitrary bits into a living object. Minimally they initialize internally used fields. They may also allocate resources (memory, files, semaphores, sockets, etc). "ctor" is a typical abbreviation for constructor. ============================================================================== [10.2] How can I make a constructor call another constructor as a primitive? No way. Dragons be here: if you call another constructor, the compiler initializes a temporary local object; it does not initialize this object. You can combine both constructors by using a default parameter, or you can share their common code in a private init() member function. ============================================================================== [10.3] What's the deal with destructors? A destructor gives an object its last rites. Destructors are used to release any resources allocated by the object. E.g., class Lock might lock a semaphore, and the destructor will release that semaphore. The most common example is when the constructor uses new, and the destructor uses delete. Destructors are a "prepare to die" member function. They are often abbreviated "dtor". ============================================================================== SECTION [11]: Operator overloading [11.1] What's the deal with operator overloading? It allows you to provide an intuitive interface to users of your class. Operator overloading allows C/C++ operators to have user-defined meanings on user-defined types (classes). Overloaded operators are syntactic sugar for function calls: class Fred { public: // ... }; #if 0 // Without operator overloading: Fred add(Fred, Fred); Fred mul(Fred, Fred); Fred f(Fred a, Fred b, Fred c) { return add(add(mul(a,b), mul(b,c)), mul(c,a)); // Yuk... } #else // With operator overloading: Fred operator+ (Fred, Fred); Fred operator* (Fred, Fred); Fred f(Fred a, Fred b, Fred c) { return a*b + b*c + c*a; } #endif ============================================================================== [11.2] But operator overloading makes my class look ugly; isn't it supposed to make my code clearer? Operator overloading makes life easier for the users of your class, not for you! Consider the following example. Some people don't like the keyword operator or the somewhat funny syntax that goes with it in the body of the class itself: class Array { public: int& operator[] (unsigned i); // Some people don't like this syntax // ... }; inline int& Array::operator[] (unsigned i) // Some people don't like this syntax { // ... } But the operator overloading syntax isn't supposed to make life easier for you when you're writing your class. It's supposed to make life easier for the users of your class: main() { Array a; a[3] = 4; // User code should be obvious and easy to understand... } Remember: in a reuse-oriented world, there will usually be many people who use your class, but there is only one person who builds it (yourself); therefore you should do things that favor the many rather than the few. ============================================================================== [11.3] What operators can/cannot be overloaded? Most can be overloaded. The only C operators that can't be are . and ?: (and sizeof, which is technically an operator). C++ adds a few of its own operators, most of which can be overloaded except :: and .*. Here's an example of the subscript operator (it returns a reference). First without operator overloading: class Array { public: #if 0 int& elem(unsigned i) { if (i>99) error(); return data[i]; } #else int& operator[] (unsigned i) { if (i>99) error(); return data[i]; } #endif private: int data[100]; }; main() { Array a; #if 0 a.elem(10) = 42; a.elem(12) += a.elem(13); #else a[10] = 42; a[12] += a[13]; #endif } ============================================================================== [11.4] Can I create a ** operator for "to-the-power-of" operations? Nope. The names of, precedence of, associativity of, and arity of operators is fixed by the language. There is no ** operator in C++, so you cannot create one for a class type. If you're in doubt, consider that x ** y is the same as x * (*y) (in other words, the compiler assumes y is a pointer). Besides, operator overloading is just syntactic sugar for function calls. Although this particular syntactic sugar can be very sweet, it doesn't add anything fundamental. I suggest you overload pow(base,exponent) (a double precision version is in ). By the way, operator^ can work for to-the-power-of, except it has the wrong precedence and associativity. ============================================================================== Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news.kei.com!nntp.coast.net!howland.reston.ans.net!usc!news.cerf.net!nic.cerf.net!mpcline From: mpcline@nic.cerf.net (Marshall Cline) Newsgroups: comp.lang.c++ Subject: C++ FAQ: posting #2/4 [IGNORE EARLIER POSTING!] Followup-To: comp.lang.c++ Date: 26 Apr 1996 21:22:14 GMT Organization: Paradigm Shift, Inc (technology consulting) Lines: 1257 Sender: cline@parashift.com Distribution: world Expires: +1 month Message-ID: <4lreq6$33d@news.cerf.net> Reply-To: cline@parashift.com (Marshall Cline) NNTP-Posting-Host: nic.cerf.net Summary: Please read this before posting to comp.lang.c++ Archive-name: C++-faq/part2_4 [PLEASE NOTE: PLEASE IGNORE THE EARLIER POSTING OF THE FAQ (it had an error in the URL for the HTML version of the FAQ)]. BIG NEWS: * The content of this document has been extensively updated. * An HTML version that is broken up by sections is now available at: http://www.cerfnet.com/~mpcline/On-Line-C++-FAQs/ Posting 2 of 4. The On-Line C++ FAQs (Frequently Asked Questions) Revised Apr 26, 1996 ============================================================================== COMMON PREFIX INFORMATION: AUTHOR: Marshall P. Cline, Ph.D., cline@parashift.com Paradigm Shift, Inc. / One Park St. / Norwood, NY 13668 315-353-6100 (voice) / 315-353-6110 (fax) COPYRIGHT: This document (the "On-Line C++ FAQs") is Copyright (C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com. All rights reserved. Copying is permmitted only under designated situations (see section [1] for permissions). NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS. THE AUTHOR PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE. On-Line-C++-FAQs != C++-FAQs-Book: Note: This document (the "On-Line C++ FAQs") is not the same as the "C++ FAQs" book (e.g., the "C++ FAQs" book is five times larger than this on-line document). The "C++ FAQs" book is available in bookstores ("C++ FAQs" by Cline and Lomow, Addison-Wesley, 1995, ISBN 0-201-58958-3; see also http://heg-school.aw.com/cseng/authors/cline/FAQ/FAQ.html). ============================================================================== OVERVIEW OF ALL SECTIONS: 1. Copying permissions 2. On-line sites that distribute this document 3. "C++-FAQs-Book" versus "On-Line-C++-FAQs" 4. List of recent changes to this document 5. How to post to comp.lang.c++ (Read Before Posting!) 6. Managerial issues 7. Classes and objects 8. References 9. Inline functions 10. Constructors and destructors 11. Operator overloading 12. Friends 13. Input/output via and 14. Freestore management 15. Exceptions and error handling 16. Const correctness 17. Basics of inheritance 18. Inheritance and virtual functions 19. Inheritance and conformance 20. Inheritance and access rules 21. Inheritance and constructors/destructors 22. Private and protected inheritance 23. Abstraction 24. Style guidelines 25. Keys for Smalltalk programmers to learn C++ 26. Reference and value semantics 27. How to mix C and C++ 28. Pointers to member functions 29. Container classes and templates 30. Class libraries 31. Compiler dependencies 32. Miscellaneous technical issues 33. Miscellaneous environmental issues ============================================================================== SECTION [12]: Friends [12.1] What is a friend? Something to allow your class to grant access to another class or function. Friends can be either functions or other classes. A class grants access privileges to its friends. Normally a developer has political and technical control over both the friend and member functions of a class (else you may need to get permission from the owner of the other pieces when you want to update your own class). ============================================================================== [12.2] Do friends violate encapsulation? If they're used properly, they actually enhance encapsulation. You often need to split a class in half when the two halves will have different numbers of instances or different lifetimes. In these cases, the two halves usually need direct access to each other (the two halves used to be in the same class, so you haven't increased the amount of code that needs direct access to a data structure; you've simply reshuffled the code into two classes instead of one). The safest way to implement this is to make the two halves friends of each other. If you use friends like just described, you'll keep private things private. People who don't understand this often make naive efforts to avoid using friendship in situations like the above, and often they actually destroy encapsulation. They either use public data (grotesque!), or they make the data accessible between the halves via public get() and set() member functions. Having a public get() and set() member function for a private datum is OK only when the private datum "makes sense" from outside the class (from a user's perspective). In many cases, these get()/set() member functions are almost as bad as public data: they hide (only) the name of the private datum, but they don't hide the existence of the private datum. Similarly, if you use friend functions as a syntactic variant of a class's public access functions, they don't violate encapsulation any more than a member function violates encapsulation. In other words, a class's friends don't violate the encapsulation barrier: along with the class's member functions, they are the encapsulation barrier. ============================================================================== [12.3] What are some advantages/disadvantages of using friend functions? They provide a degree of freedom in the interface design options. Member functions and friend functions are equally privileged (100% vested). The major difference is that a friend function is called like f(x), while a member function is called like x.f(). Thus the ability to choose between member functions (x.f()) and friend functions (f(x)) allows a designer to select the syntax that is deemed most readable, which lowers maintenance costs. The major disadvantage of friend functions is that they require an extra line of code when you want dynamic binding. To get the effect of a virtual friend, the friend function should call a hidden (usually protected:) virtual member function. For example: class Base { public: friend void f(Base& b); // ... protected: virtual void do_f(); // ... }; inline void f(Base& b) { b.do_f(); } class Derived : public Base { public: // ... protected: virtual void do_f(); // "Override" the behavior of f(Base& b) // ... }; void userCode(Base& b) { f(b); } The statement f(b) in userCode(Base&) will invoke b.do_f(), which is virtual. This means that Derived::do_f() will get control if b is actually a object of class Derived. Note that Derived overrides the behavior of the protected: virtual member function do_f(); it does not have its own variation of the friend function, f(Base&). ============================================================================== [12.4] What does it mean that "friendship is neither inherited nor transitive"? I may declare you as my friend, but that doesn't mean I necessarily trust either your kids or your friends. * I don't necessarily trust the kids of my friends. The privileges of friendship aren't inherited. Derived classes of a friend aren't necessarily friends. If class Fred declares that class Base is a friend, classes derived from Base don't have any automatic special access rights to Fred objects. * I don't necessarily trust the friends of my friends. The privileges of friendship aren't transitive. A friend of a friend isn't necessarily a friend. If class Fred declares class Wilma as a friend, and class Wilma declares class Betty as a friend, class Betty doesn't necessarily have any special access rights to Fred objects. ============================================================================== [12.5] Should my class declare a member function or a friend function? Use a member when you can, and a friend when you have to. Sometimes friends are syntactically better (e.g., in class Fred, friend functions allow the Fred parameter to be second, while members require it to be first). Another good use of friend functions are the binary infix arithmetic operators. E.g., aComplex + aComplex should be defined as a friend rather than a member if you want to allow aFloat + aComplex as well (member functions don't allow promotion of the left hand argument, since that would change the class of the object that is the recipient of the member function invocation). In other cases, choose a member function over a friend function. ============================================================================== SECTION [13]: Input/output via and [13.1] How can I provide printing for a class Fred? Provide a friend operator<<: class Fred { public: friend ostream& operator<< (ostream& o, const Fred& fred); // ... private: int i_; // Just for illustration }; ostream& operator<< (ostream& o, const Fred& fred) { return o << fred.i_; } We use a friend rather than a member since the Fred parameter is second rather than first. Input is similar. The syntax follows (note that the parameter is "Fred&", not "const Fred&"): class Fred { public: friend istream& operator>> (istream& i, Fred& fred); // ... private: int i_; // Just for illustration }; istream& operator>> (istream& i, Fred& fred) { return i >> fred.i_; } ============================================================================== [13.2] Why should I use instead of the traditional ? Increase type safety, reduce errors, improve performance, allow extensibility, and provide subclassability. printf() is arguably not broken, and scanf() is perhaps livable despite being error prone, however both are limited with respect to what C++ I/O can do. C++ I/O (using << and >>) is, relative to C (using printf() and scanf()): * Better type safety: With , the type of object being I/O'd is known statically by the compiler. In contrast, uses "%" fields to figure out the types dynamically. * Less error prone: With , there are no redundant "%" tokens that have to be consistent with the actual objects being I/O'd. Removing redundancy removes a class of errors. * Extensible: The C++ mechanism allows new user-defined types to be I/O'd without breaking existing code. Imagine the chaos if everyone was simultaneously adding new incompatible "%" fields to printf() and scanf()?!). * Subclassable: The C++ mechanism is built from real classes such as ostream and istream. Unlike 's FILE*, these are real classes and hence subclassable. This means you can have other user-defined things that look and act like streams, yet that do whatever strange and wonderful things you want. You automatically get to use the zillions of lines of I/O code written by users you don't even know, and they don't need to know about your "extended stream" class. ============================================================================== [13.3] Why does my input seem to process past the end of file? Because the eof state is not set until after a read is attempted past the end of file. That is, reading the last byte from a file does not set the eof state. For example, the following code has an off-by-one error with the count i: int i = 0; while (! cin.eof()) { // WRONG! cin >> x; ++i; // Work with x ... } What you really need is: int i = 0; while (cin >> x) { // RIGHT! ++i; // Work with x ... } ============================================================================== [13.4] Why is my program ignoring my input request after the first iteration? Because the numerical extractor leaves non-digits behind in the input buffer. If your code looks like this: char name[1000]; int age; for (;;) { cout << "Name: "; cin >> name; cout << "Age: "; cin >> age; } What you really want is: for (;;) { cout << "Name: "; cin >> name; cout << "Age: "; cin >> age; cin.ignore(INT_MAX, '\n'); } ============================================================================== [13.5] How can I "reopen" cin and cout in binary mode under DOS and/or OS/2? This is implementation dependent. Check with your compiler's documentation. For example, suppose you want to do binary I/O using cin and cout. Suppose further that your operating system (such as DOS or OS/2) insists on translating "\r\n" into "\n" on input from cin, and "\n" to "\r\n" on output to cout or cerr. Unfortunately there is no standard way to cause cin, cout, and/or cerr to be opened in binary mode. Closing the streams and attempting to reopen them in binary mode might have unexpected or undesirable results. On systems where it makes a difference, the implementation might provide a way to make them binary streams, but you would have to check the manuals to find out. ============================================================================== SECTION [14]: Freestore management [14.1] Does delete p delete the pointer p, or the pointed-to-data, *p? The pointed-to-data. The keyword should really be delete_the_thing_pointed_to_by. The same abuse of English occurs when freeing the memory pointed to by a pointer in C: free(p) really means free_the_stuff_pointed_to_by(p). ============================================================================== [14.2] Can I free() pointers allocated with new? Can I delete pointers allocated with malloc()? No! It is perfectly legal, moral, and wholesome to use malloc() and delete in the same program, or to use new and free() in the same program. But it is illegal, immoral, and despicable to call free() with a pointer allocated via new, or to call delete on a pointer allocated via malloc(). Beware! I occasionally get email from people telling me that it works OK for them on machine X and compiler Y. That does not make it right! Sometimes people say, "But I'm just working with an array of char." Nonetheless do not mix malloc() and delete on the same pointer, or new and free() on the same pointer! If you allocated via p = new char[n], you must use delete[] p; you must not use free(p). Or if you allocated via p = malloc(n), you must use free(p); you must not use delete[] p or delete p! Mixing these up could cause a catastrophic failure at runtime if the code was ported to a new machine, a new compiler, or even a new version of the same compiler. You have been warned. ============================================================================== [14.3] Why should I use new instead of trustworthy old malloc()? Constructors/destructors, type safety, overridability. * Constructors/destructors: unlike malloc(sizeof(Fred)), new Fred() calls Fred's constructor. Similarly, delete p calls *p's destructor. * Type safety: malloc() returns a void* which isn't type safe. new Fred() returns a pointer of the right type (a Fred*). * Overridability: new is an operator that can be overridden by a class, while malloc() is not overridable on a per-class basis. ============================================================================== [14.4] Why shouldn't I use realloc() on pointers allocated via new? To save you from disaster. When realloc() has to copy the allocation, it uses a bitwise copy operation, which will tear many C++ objects to shreds. C++ objects should be allowed to copy themselves. They use their own copy constructor or assignment operator. ============================================================================== [14.5] How do I allocate / unallocate an array of things? Use p = new T[n] and delete[] p: Fred* p = new Fred[100]; // ... delete[] p; Any time you allocate an array of objects via new (usually with the [n] in the new expression), you must use [] in the delete statement. This syntax is necessary because there is no syntactic difference between a pointer to a thing and a pointer to an array of things (something we inherited from C). ============================================================================== [14.6] What if I forget the [] when deleteing array allocated via new T[n]? All life comes to a catastrophic end. It is the programmer's --not the compiler's-- responsibility to get the connection between new T[n] and delete[] p correct. If you get it wrong, neither a compile-time nor a run-time error message will be generated by the compiler. Heap corruption is a likely result. Or worse. Your program will probably die. ============================================================================== [14.7] Can I drop the [] when deleteing array of some built-in type (char, int, etc)? No! Sometimes programmers think that the [] in the delete[] p only exists so the compiler will call the appropriate destructors for all elements in the array. Because of this reasoning, they assume that an array of some built-in type such as char or int can be deleted without the []. E.g., they assume the following is valid code: void userCode(int n) { char* p = new char[n]; // ... delete p; // <---- ERROR! Should be delete[] p ! } But the above code is wrong, and it can cause a disaster at runtime. In particular, the code that's called for delete p is operator delete(void*), but the code that's called for delete[] p is operator delete[](void*). The default behavior for the latter is to call the former, but users are allowed to replace the latter with a different behavior (in which case they would normally also replace the corresponding new code in operator new[](size_t)). If they replaced the delete[] code so it wasn't compatible with the delete code, and you called the wrong one (i.e., if you said delete p rather than delete[] p), you could end up with a disaster at runtime. ============================================================================== [14.8] Is it legal (and moral) for a member function to say delete this? As long as you're careful, it's OK for an object to commit suicide (delete this). Here's how I define "careful": 1. You must be absolutely 100% positive sure that this object was allocated via new (not by "new[]", nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new). 2. You must be absolutely 100% positive sure that your member function will be the last member function invoked on this object. 3. You must be absolutely 100% positive sure that the rest of your member function (after the delete this line) doesn't touch any piece of this object (including calling any other member functions or touching any data members). 4. You must be absolutely 100% positive sure that no one even touches the this pointer itself after the delete this line. In other words, you must not examine it, compare it with another pointer, compare it with NULL, print it, cast it, do anything with it. Naturally the usual caveats apply in cases where your this pointer is a pointer to a base class and the destructor isn't virtual. ============================================================================== [14.9] How do I allocate multidimensional arrays using new? There are many ways to do this, depending on how flexible you want the array sizing to be. On one extreme, if you know all the dimensions at compile-time, you can allocate multidimensional arrays statically (as in C): class Fred { /*...*/ }; void manipulateArray() { Fred matrix[10][20]; // Use matrix[i][j]... // No need for explicit deallocation } On the other extreme, if you want to allow the various slices of the matrix to have a different sizes, you can allocate everything off the freestore. For example, in the following function, nrows is the number of rows in the array (i.e., the valid row numbers are from 0 to nrows-1 inclusive), and array element ncols[r] is the number of columns in row r (where r in the range 0 to nrows-1 inclusive): void manipulateArray(unsigned nrows, unsigned ncols[]) { Fred** matrix = new Fred*[nrows]; for (unsigned r = 0; r < nrows; ++r) matrix[r] = new Fred[ ncols[r] ]; // ... // Deletion is the opposite of allocation: for (r = nrows; r > 0; --r) delete[] matrix[r-1]; delete[] matrix; } Note the funny use of matrix[r-1] in the deletion process. This prevents wrap-around of the unsigned value when r goes one step past zero. ============================================================================== [14.10] Does C++ have arrays whose length can be specified at run-time? Yes, in the sense that STL has a vector template that provides this behavior. See on "STL" in the "Libraries" section. No, in the sense that built-in array types need to have their length specified at compile time. Yes, in the sense that even built-in array types can specify the first index bounds at run-time. E.g., comparing with the previous FAQ, if you only need the first array dimension to vary then you can just ask new for an array of arrays, rather than an array of pointers to arrays: const unsigned ncols = 100; // ncols = number of columns in the array class Fred { /*...*/ }; void manipulateArray(unsigned nrows) // nrows = number of rows in the array { Fred (*matrix)[ncols] = new Fred[nrows][ncols]; // ... delete[] matrix; } You can't do this if you need anything other than the first dimension of the array to change at run-time. ============================================================================== [14.11] How can I ensure objects of my class are always created via new rather than as locals or global/static objects? Make sure the class's constructors are private:, and define friend or static functions that return a pointer to the objects created via new (make the constructors protected: if you want to allow derived classes). class Fred { public: static Fred* create() { return new Fred(); } static Fred* create(int i) { return new Fred(i); } static Fred* create(const Fred& fred) { return new Fred(fred); } virtual ~Fred(); private: // Ctors are private; only want to allow dynamically allocated Fred's Fred(); Fred(int i); Fred(const Fred& fred); }; main() { Fred* p = Fred::create(5); // ... delete p; } ============================================================================== SECTION [15]: Exceptions and error handling [15.1] How can I handle a constructor that fails? Throw an exception. Constructors don't have a return type, so it's not possible to use error codes. The best way to signal constructor failure is therefore to throw an exception. If you don't have or won't use exceptions, here's a work-around. If a constructor fails, the constructor can put the object into a "zombie" state. Do this by setting an internal status bit so the object acts sort of like its dead even though it is technically still alive. Then add a query ("inspector") member function to check this "zombie" bit so users of your class can find out if their object is truly alive, or if it's a zombie (i.e., a "living dead" object). Also you'll probably want to have your other member functions check this zombie bit, and, if the object isn't really alive, do a no-op (or perhaps something more obnoxious such as abort()). This is really ugly, but it's the best you can do if you can't (or don't want to) use exceptions. ============================================================================== [15.2] How should I handle resources if my constructors may throw exceptions? Every data member inside your object should clean up its own mess. If a constructor throws an exception, the object's destructor is not run. If your object has already done something that needs to be undone (such as allocating some memory, opening a file, or locking a semaphore), this "stuff that needs to be undone" must be remembered by a data member inside the object. For example, rather than allocating memory into a raw Fred* data member, put the allocated memory into a "smart pointer" member object, and the destructor of this smart pointer will delete the Fred object when the smart pointer dies. ============================================================================== SECTION [16]: Const correctness [16.1] What is "const correctness"? A good thing. It means using the keyword const to ensure const objects don't get mutated. For example, if you wanted to create a function f() that accepted a String, plus you want to promise callers not to change the caller's String that gets passed to f(), you can have f() receive its String parameter . . . * void f(String s); // Pass by value * void f(const String& s); // Pass by reference-to-const * void f(const String* sptr); // Pass by pointer-to-const Attempted changes to the caller's String within any of these functions would be flagged by the compiler as an error at compile-time. Neither run-time space nor speed is degraded. On the other hand, if you wanted to create a function g() that But you cannot have f() receive its String parameter . . . As an opposite example, if you wanted to create a function g() that accepted a String, but you want to let callers know that g() might change the caller's String object, you can have g() receive its String parameter . . . * void g(String& s); // Pass by reference-to-non-const * void g(String* sptr); // Pass by pointer-to-non-const ============================================================================== [16.2] How is "const correctness" related to ordinary type safety? Declaring the const-ness of a parameter is just another form of type safety. It is almost as if a const String, for example, is a different class than an ordinary String, since the const variant is missing the various mutative operations in the non-const variant (e.g., you can imagine that a const String simply doesn't have an assignment operator). If you find ordinary type safety helps you get systems correct (it does; especially in large systems), you'll find const correctness helps also. ============================================================================== [16.3] Should I try to get things const correct "sooner" or "later"? At the very, very, very beginning. Back-patching const correctness results in a snowball effect: every const you add "over here" requires four more to be added "over there." ============================================================================== [16.4] What is a "const member function"? A member function that inspects (rather than mutates) its object. A const member function is indicated by a const suffix just after the member function's parameter list. Member functions with a const suffix are called "const member functions" or "inspectors." Member functions without a const suffix are called "non-const member functions" or "mutators." class Fred { public: void inspect() const; // This member promises NOT to change *this void mutate(); // This member function might change *this }; void userCode(Fred& changeable, const Fred& unchangeable) { changeable.inspect(); // OK: doesn't change a changeable object changeable.mutate(); // OK: changes a changeable object unchangeable.inspect(); // OK: doesn't change an unchangeable object unchangeable.mutate(); // ERROR: attempt to change unchangeable object } The error in unchangeable.mutate() is caught at compile time. There is no runtime space or speed penalty for const. The trailing const on inspect() member function means that the abstract (client-visible) state of the object isn't going to change. This is slightly different from promising that the "raw bits" of the object's struct aren't going to change. C++ compilers aren't allowed to take the "bitwise" interpretation unless they can solve the aliasing problem, which normally can't be solved (i.e., a non-const alias could exist which could modify the state of the object). Another (important) insight from this aliasing issue: pointing at an object with a const pointer doesn't guarantee that the object won't change; it promises only that the object won't change via that pointer). ============================================================================== [16.5] What do I do if I want to update an "invisible" data member inside a const member function? Use mutable, or use const_cast. A small percentage of inspectors need to make innocuous changes to data members (e.g., a Set object might want to cache its last lookup in hopes of improving the performance of its next lookup). By saying the changes are "innocuous," I mean that the changes wouldn't be visible from outside the object's interface (otherwise the member function would be a mutator rather than an inspector). When this happens, the data member which will be modified should be marked as mutable (put the mutable keyword just before the data member's declaration; i.e., in the same place where you could put const). This tells the compiler that the data member is allowed to change during a const member function. If your compiler doesn't support the mutable keyword, you can cast away the const'ness of this via the const_cast keyword. E.g., in Set::lookup() const, you might say, Set* self = const_cast(this); After this line, self will have the same bits as this (e.g., self == this), but self is a Set* rather than a const Set*. Therefore you can use self to modify the object pointed to by this. ============================================================================== [16.6] Does const_cast mean lost optimization opportunities? In theory, yes; in practice, no. Even if the language outlawed const_cast, the only way to avoid flushing the register cache across a const member function call would be to solve the aliasing problem (i.e., to ensure that there are no non-const pointers that point to the object). This can happen only in rare cases (when the object is constructed in the scope of the const member function invocation, and when all the non-const member function invocations between the object's construction and the const member function invocation are statically bound, and when every one of these invocations is also inlined, and when the constructor itself is inlined, and when any member functions the constructor calls are inline). ============================================================================== SECTION [17]: Basics of inheritance [17.1] Is inheritance important to C++? Yep. Inheritance is what separates abstract data type (ADT) programming from OO programming. ============================================================================== [17.2] When would I use inheritance? As a specification device. Human beings abstract things on two dimensions: part-of and kind-of. A Ford Taurus is-a-kind-of-a Car, and a Ford Taurus has-a Engine, Tires, etc. The part-of hierarchy has been a part of software since the ADT style became relevant; inheritance adds "the other" major dimension of decomposition. ============================================================================== [17.3] How do you express inheritance in C++? By the : public syntax: class Car : public Vehicle { public: // ... }; We state the above relationship in several ways: * Car is "a kind of a" Vehicle * Car is "derived from" Vehicle * Car is "a specialized" Vehicle * Car is the "subclass" of Vehicle * Vehicle is the "base class" of Car * Vehicle is the "superclass" of Car (this not as common in the C++ community) (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== [17.4] Is it OK to convert a pointer from a derived class to its base class? Yes. An object of a derived class is a kind of the base class. Therefore the conversion from a derived class pointer to a base class pointer is perfectly safe, and happens all the time. For example, if I am pointing at a car, I am in fact pointing at a vehicle, so converting a Car* to a Vehicle* is perfectly safe and normal: void f(Vehicle* v); void g(Car* c) { f(c); } // Perfectly safe; no cast (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== [17.5] Derived* --> Base* works OK; why doesn't Derived** --> Base** work? C++ allows a Derived* to be converted to a Base*, since a Derived object is a kind of a Base object. However trying to convert a Derived** to a Base** is flagged as an error. Although this error may not be obvious, it is nonetheless a good thing. For example, if you could convert a Car** to a Vehicle**, and if you could similarly convert a NuclearSubmarine** to a Vehicle**, you could assign those two pointers and end up making a Car* point at a NuclearSubmarine: class Vehicle { /*...*/ }; class Car : public Vehicle { /*...*/ }; class NuclearSubmarine : public Vehicle { /*...*/ }; main() { Car car; Car* carPtr = &car; Car** carPtrPtr = &carPtr; Vehicle** vehiclePtrPtr = carPtrPtr; // This is an error in C++ Vehicle* vehiclePtr = *vehiclePtrPtr; NuclearSubmarine sub; NuclearSubmarine* subPtr = ⊂ vehiclePtr = subPtr; // This last line would have caused carPtr to point to sub ! } In other words, if the Derived** --> Base** conversion was allowed, the Base** could be dereferenced (yielding a Base*), and the Base* could be made to point to an object of a different derived class, which could cause serious problems for national security (who knows what would happen if you invoked the openGasCap() member function on what you thought was a Car, but in reality it was a NuclearSubmarine!!).. ============================================================================== [17.6] Is a parking-lot-of-Car a kind-of parking-lot-of-Vehicle? Nope. I know it sounds strange, but it's true. You can think of this as a direct consequence of the previous FAQ, or you can reason it this way: if the kind-of relationship were valid, then someone could point a parking-lot-of-Vehicle pointer at a parking-lot-of-Car. But parking-lot-of-Vehicle has a addNewVehicleToParkingLot(Vehicle&) member function which can add any Vehicle object to the parking lot. This would allow you to park a NuclearSubmarine in a parking-lot-of-Car. Certainly it would be surprising if someone removed what they thought was a Car from the parking-lot-of-Car, only to find that it is actually a NuclearSubmarine. Another way to say this truth: a container of Thing is not a kind-of container of Anything even if a Thing is a kind-of an Anything. Swallow hard; it's true. You don't have to like it. But you do have to accept it. One last example which we use in our OO/C++ training courses: "A Bag-of-Apple is not a kind-of Bag-of-Fruit." If a Bag-of-Apple could be passed as a Bag-of-Fruit, someone could put a Banana into the Bag, even though it is supposed to only contain Apples! ============================================================================== [17.7] Is an array of Derived a kind-of array of Base? Nope. This is a corollary of the previous FAQ. Unfortunately this one can get you into a lot of hot water. Consider this: class Base { public: virtual void f(); // 1 }; class Derived : public Base { public: // ... private: int i_; // 2 }; void userCode(Base* arrayOfBase) { arrayOfBase[1].f(); // 3 } main() { Derived arrayOfDerived[10]; // 4 f(arrayOfDerived); // 5 } The compiler thinks this is perfectly type-safe. Line 5 converts a Derived* to a Base*. But in reality it is horrendously evil: since Derived is larger than Base, the pointer arithmetic done on line 3 is incorrect: the compiler uses sizeof(Base) when computing the address for arrayOfBase[1], yet the array is an array of Derived, which means the address computed on line 3 (and the subsequent invocation of member function f()) isn't even at the beginning of any object! It's smack in the middle of a Derived object. Assuming your compiler uses the usual approach to virtual functions, this will reinterpret the int i_ of the first Derived as if it pointed to a virtual table, it will follow that "pointer" (which at this point means we're digging stuff out of a random memory location), and grab one of the first few words of memory at that location and interpret them as if they were the address of a C++ member function, then load that (random memory location) into the instruction pointer and begin grabbing machine instructions from that memory location. The chances of this crashing are very high. The root problem is that C++ can't distinguish between a pointer-to-a-thing and a pointer-to-an-array-of-things. Naturally C++ "inherited" this feature from C. NOTE: If we had used an array-like class (e.g., STL's vector) instead of using a raw array, this problem would have been properly trapped as an error at compile time rather than a run-time disaster. ============================================================================== [17.8] Does array-of-Derived is-not-a-kind-of array-of-Base mean arrays are bad? Yes, arrays are evil. (only half kidding). Seriously, arrays are very closely related to pointers, and pointers are notoriously difficult to deal with. But if you have a complete grasp of why the above few FAQs were a problem from a design perspective (e.g., if you really know why a container of Thing is not a kind-of container of Anything), and if you think everyone else who will be maintaining your code also has a full grasp on these OO design truths, then you should feel free to use arrays. But if you're like most people, you should use a template container class such as STL's vector rather than raw arrays. ============================================================================== SECTION [18]: Inheritance and virtual functions [18.1] What is a "virtual member function"? A virtual function allows derived classes to replace the implementation provided by the base class. The compiler ensures the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class. The derived class can either fully replace ("override") the base class member function, or the derived class can partially replace ("augment") the base class member function. The latter is accomplished by having the derived class member function call the base class member function, if desired. ============================================================================== [18.2] How can C++ achieve dynamic binding yet also static typing? When you have a pointer to an object, the object may actually be of a class that is derived from the class of the pointer (e.g., a Vehicle* that is actually pointing to a Car object). Thus there are two types: the (static) type of the pointer (Vehicle, in this case), and the (dynamic) type of the pointed-to object (Car, in this case). "Static typing" means that the legality of a member function invocation is checked at the earliest possible moment: by the compiler at compile time. The compiler uses the static type of the pointer to determine whether the member function invocation is legal. If the type of the pointer can handle the member function, certainly the pointed-to object can handle it as well. E.g., if Vehicle has a certain member function, certainly Car also has that member function since Car is a kind-of Vehicle. "Dynamic binding" means that the address of the code in a member function invocation is determined at the last possible moment: based on the dynamic type of the object at run time. It is called "dynamic binding" because the binding to the code that actually gets called is accomplished dynamically (at run time). ============================================================================== [18.3] Should a derived class replace ("override") a non-virtual function from a base class? It's legal, but it ain't moral. Experienced C++ programmers will sometimes redefine a non-virtual function (e.g., the derived class implementation might make better use of the derived class's resources for efficiency), or to get around the hiding rule (see below). However the client-visible effects must be identical, since non-virtual functions are dispatched based on the static type of the pointer/reference rather than the dynamic type of the pointed-to/referenced object. ============================================================================== [18.4] What's the meaning of, Warning: Derived::f(int) hides Base::f(float)? It means you're going to die. Here's the mess you're in: if Derived declares a member function named f(), and Base declares a member function named f() with a different signature (e.g., different parameter types and/or constness), then the Base f() is "hidden" rather than "overloaded" or "overridden" (even if the Base f() is virtual). Here's how you get out of the mess: Derived must redefine the Base member function(s) that are hidden (even if they are non-virtual). Normally this re-definition merely calls the appropriate Base member function. E.g., class Base { public: void f(int); }; class Derived : public Base { public: void f(double); void f(int i) { Base::f(i); } // The redefinition merely calls Base::f(int) }; ============================================================================== SECTION [19]: Inheritance and conformance [19.1] Should I hide member functions that were public in my base class? Never, never, never do this. Never. Never! Attempting to hide (eliminate, revoke, privatize) inherited public member functions is an all-too-common design error. It usually stems from muddy thinking. (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== [19.2] Is a Circle a kind-of an Ellipse? Not if Ellipse promises to be able to change its size asymmetrically. For example, suppose Ellipse has a setSize(x,y) member function, and suppose this member function promises the Ellipse's width() will be x, and its height() will be y. In this case, Circle can't be a kind-of Ellipse. Simply put, if Ellipse can do something Circle can't, then Circle can't be a kind of Ellipse. This leaves two potential (valid) relationships between Circle and Ellipse: * Make Circle and Ellipse completely unrelated classes * Derive Circle and Ellipse from a base class representing "Ellipses that can't necessarily perform an unequal-setSize() operation" In the first case, Ellipse could be derived from class AsymmetricShape, and setSize(x,y) could be introduced in AsymmetricShape. However Circle could be derived from SymmetricShape which has a setSize(size) member function. In the second case, class Oval could only have setSize(size) which sets both the width() and the height() to size. Ellipse and Circle could both inherit from Oval. Ellipse --but not Circle-- could add the setSize(x,y) operation (see the "hiding rule" for a caveat if the same member function name setSize() is used for both operations). (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== [19.3] Are there other options to the "Circle is/isnot kind-of Ellipse" dilemma? If you claim that all Ellipses can be squashed asymmetrically, and you claim that Circle is a kind-of Ellipse, and you claim that Circle can't be squashed asymmetrically, clearly you've got to adjust (revoke, actually) one of your claims. Thus you've either got to get rid of Ellipse::setSize(x,y), get rid of the inheritance relationship between Circle and Ellipse, or admit that your Circles aren't necessarily circular. Here are the two most common traps new OO/C++ programmers regularly fall into. They attempt to use coding hacks to cover up a broken design (they redefine Circle::setSize(x,y) to throw an exception, call abort(), choose the average of the two parameters, or to be a no-op). Unfortunately all these hacks will surprise users, since users are expecting width() == x and height() == y. The one thing you must not do is surprise your users. If it is important to you to retain the "Circle is a kind-of Ellipse" inheritance relationship, you can weaken the promise made by Ellipse's setSize(x,y). E.g., you could change the promise to, "This member function might set width() to x and/or it might set height() to y, or it might do nothing". Unfortunately this dilutes the contract into dribble, since the user can't rely on any meaningful behavior. The whole hierarchy therefore begins to be worthless (it's hard to convince someone to use an object if you have to shrug your shoulders when asked what the object does for them). (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== [19.4] But I have a Ph.D. in Mathematics, and I'm sure a Circle is a kind of an Ellipse! Does this mean Marshall Cline is stupid? Or that C++ is stupid? Or that OO is stupid? Actually, it doesn't mean any of these things. The sad reality is that it means your intuition is wrong. Look, I have received and answered dozens of passionate email messages about this subject. I have taught it hundreds of times to thousands of software professionals all over the place. I know it goes against your intuition. But trust me; your intuition is wrong. The real problem is your intuitive notion of "kind of" doesn't match the OO notion of proper inheritance (technically called "subtyping"). The bottom line is that the derived class objects must be substitutable for the base class objects. In the case of Circle/Ellipse, the setSize(x,y) member function violates this substitutability. You have three choices: [1] remove the setSize(x,y) member function from Ellipse (thus breaking existing code that calls the setSize(x,y) member function), [2] allow a Circle to have a different height than width (an asymmetrical circle; hmmm), or [3] drop the inheritance relationship. Sorry, but there simply are no other choices. Note that some people mention the option of deriving both Circle and Ellipse from a third common base class, but that's just a variant of option [3] above. Another way to say this is that you have to either make the base class weaker (in this case braindamage Ellipse to the point that you can't set its width and height to different values), or make the derived class stronger (in this case empower a Circle with the ability to be both symmetric and, ahem, asymmetric). When neither of these is very satisfying (such as in the Circle/Ellipse case), one normally simply removes the inheritance relationship. If the inheritance relationship simply has to exist, you may need to remove the mutator member functions (setHeight(y), setWidth(x), and setSize(x,y)) from the base class. (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== [19.5] But my problem doesn't have anything to do with circles and ellipses, so what good is that silly example to me? Ahhh, there's the rub. You think the Circle/Ellipse example is just a silly example. But in reality, your problem is an isomorphism to that example. I don't care what your inheritance problem is, but all (yes all) bad inheritances boil down to the Circle-is-not-a-kind-of-Ellipse example. Here's why: Bad inheritances always have a base class with an extra capability (often an extra member function or two; sometimes an extra promise made by one or a combination of member functions) that a derived class can't satisfy. You've either got to make the base class weaker, make the derived class stronger, or eliminate the proposed inheritance relationship. I've seen lots and lots and lots of these bad inheritance proposals, and believe me, they all boil down to the Circle/Ellipse example. Therefore, if you truly understand the Circle/Ellipse example, you'll be able to recognize bad inheritance everywhere. If you don't understand what's going on with the Circle/Ellipse problem, the chances are high that you'll make some very serious and very expensive inheritance mistakes. Sad but true. (Note: this FAQ has to do with public inheritance; private and protected inheritance are different; see below.) ============================================================================== SECTION [20]: Inheritance and access rules [20.1] What's the difference between public:, private:, and protected:? private: is discussed in the previous section, and public: means "anyone can access it." The third option, protected:, makes a member (either data member or member function) accessible to subclasses. ============================================================================== [20.2] Why can't my derived class access private things from my base class? To protect you from future changes to the base class. Derived classes do not get access to private members of a base class. This effectively "seals off" the derived class from any changes made to the private members of the base class. ============================================================================== [20.3] How can I protect subclasses from breaking when I change internal parts? A class has two distinct interfaces for two distinct sets of clients: * It has a public: interface that serves unrelated classes * It has a protected: interface that serves derived classes Unless you expect all your subclasses to be built by your own team, you should consider making your base class's bits be private:, and use protected: inline access functions by which derived classes will access the private data in the base class. This way the private bits can change, but the derived class's code won't break unless you change the protected access functions. ============================================================================== SECTION [21]: Inheritance and constructors/destructors [21.1] When my base class's constructor calls a virtual function, why doesn't my derived class's override of that virtual function get invoked? During the class Base's constructor, the object isn't yet a Derived, so if Base::Base() calls a virtual function virt(), the Base::virt() will be invoked, even if Derived::virt() exists. Similarly, during Base's destructor, the object is no longer a Derived, so when Base::~Base() calls virt(), Base::virt() gets control, not the Derived::virt() override. You'll quickly see the wisdom of this approach when you imagine the disaster if Derived::virt() touched a member object from class Derived. ============================================================================== [21.2] Does a derived class destructor need to explicitly call the base destructor? No. Never explicitly call a destructor (where "never" means "rarely"). A derived class's destructor (whether or not you explicitly define one) automatically invokes the destructors for member objects and base class subobjects. Member objects are destroyed in the reverse order they appear within the class, then base class subobjects are destroyed in the reverse order that they appear in the class's list of base classes. You should explicitly call a destructor only in esoteric situations, such as when destroying an object created by the "placement new operator." ============================================================================== Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!paperboy.osf.org!bone.think.com!blanket.mitre.org!news.mathworks.com!newsfeed.internetmci.com!panix!news.columbia.edu!news.new-york.net!wlbr!news.cerf.net!nic.cerf.net!mpcline From: mpcline@nic.cerf.net (Marshall Cline) Newsgroups: comp.lang.c++ Subject: C++ FAQ: posting #3/4 [IGNORE EARLIER POSTING!] Followup-To: comp.lang.c++ Date: 26 Apr 1996 21:22:27 GMT Organization: Paradigm Shift, Inc (technology consulting) Lines: 1058 Sender: cline@parashift.com Distribution: world Expires: +1 month Message-ID: <4lreqj$33f@news.cerf.net> Reply-To: cline@parashift.com (Marshall Cline) NNTP-Posting-Host: nic.cerf.net Summary: Please read this before posting to comp.lang.c++ Archive-name: C++-faq/part3_4 [PLEASE NOTE: PLEASE IGNORE THE EARLIER POSTING OF THE FAQ (it had an error in the URL for the HTML version of the FAQ)]. BIG NEWS: * The content of this document has been extensively updated. * An HTML version that is broken up by sections is now available at: http://www.cerfnet.com/~mpcline/On-Line-C++-FAQs/ Posting 3 of 4. The On-Line C++ FAQs (Frequently Asked Questions) Revised Apr 26, 1996 ============================================================================== COMMON PREFIX INFORMATION: AUTHOR: Marshall P. Cline, Ph.D., cline@parashift.com Paradigm Shift, Inc. / One Park St. / Norwood, NY 13668 315-353-6100 (voice) / 315-353-6110 (fax) COPYRIGHT: This document (the "On-Line C++ FAQs") is Copyright (C) 1991-96 Marshall P. Cline, Ph.D., cline@parashift.com. All rights reserved. Copying is permmitted only under designated situations (see section [1] for permissions). NO WARRANTY: THIS WORK IS PROVIDED ON AN "AS IS" BASIS. THE AUTHOR PROVIDES NO WARRANTY WHATSOEVER, EITHER EXPRESS OR IMPLIED, REGARDING THE WORK, INCLUDING WARRANTIES WITH RESPECT TO ITS MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE. On-Line-C++-FAQs != C++-FAQs-Book: Note: This document (the "On-Line C++ FAQs") is not the same as the "C++ FAQs" book (e.g., the "C++ FAQs" book is five times larger than this on-line document). The "C++ FAQs" book is available in bookstores ("C++ FAQs" by Cline and Lomow, Addison-Wesley, 1995, ISBN 0-201-58958-3; see also http://heg-school.aw.com/cseng/authors/cline/FAQ/FAQ.html). ============================================================================== OVERVIEW OF ALL SECTIONS: 1. Copying permissions 2. On-line sites that distribute this document 3. "C++-FAQs-Book" versus "On-Line-C++-FAQs" 4. List of recent changes to this document 5. How to post to comp.lang.c++ (Read Before Posting!) 6. Managerial issues 7. Classes and objects 8. References 9. Inline functions 10. Constructors and destructors 11. Operator overloading 12. Friends 13. Input/output via and 14. Freestore management 15. Exceptions and error handling 16. Const correctness 17. Basics of inheritance 18. Inheritance and virtual functions 19. Inheritance and conformance 20. Inheritance and access rules 21. Inheritance and constructors/destructors 22. Private and protected inheritance 23. Abstraction 24. Style guidelines 25. Keys for Smalltalk programmers to learn C++ 26. Reference and value semantics 27. How to mix C and C++ 28. Pointers to member functions 29. Container classes and templates 30. Class libraries 31. Compiler dependencies 32. Miscellaneous technical issues 33. Miscellaneous environmental issues ============================================================================== SECTION [22]: Private and protected inheritance [22.1] How do you express "private inheritance"? When you use : private instead of : public. E.g., class Foo : private Bar { public: // ... }; ============================================================================== [22.2] How are "private inheritance" and "composition" similar? private inheritance is a syntactic variant of composition (has-a). E.g., the "Car has-a Engine" relationship can be expressed using composition: class Engine { public: Engine(int numCylinders); void start(); // Starts this Engine }; class Car { public: Car() : e_(8) { } // Initializes this Car with 8 cylinders void start() { e_.start(); } // Start this Car by starting its Engine private: Engine e_; // Car has-a Engine }; The same "has-a" relationship can also be expressed using private inheritance: class Car : private Engine { // Car has-a Engine public: Car() : Engine(8) { } // Initializes this Car with 8 cylinders Engine::start; // Start this Car by starting its Engine }; There are several similarities between these two forms of composition: * In both cases there is exactly one Engine member object contained in a Car * In neither case can users (outsiders) convert a Car* to an Engine* There are also several distinctions: * The first form is needed if you want to contain several Engines per Car * The second form can introduce unnecessary multiple inheritance * The second form allows members of Car to convert a Car* to an Engine* * The second form allows access to the protected members of the base class * The second form allows Car to override Engine's virtual functions Note that private inheritance is usually used to gain access into the protected: members of the base class, but this is usually a short-term solution (translation: a band-aid; see below). ============================================================================== [22.3] Which should I prefer: composition or private inheritance? Use composition when you can, private inheritance when you have to. Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code. A legitimate, long-term use for private inheritance is when you want to build a class Fred that uses code in a class Wilma, and the code from class Wilma needs to invoke member functions from your new class, Fred. In this case, Fred calls non-virtuals in Wilma, and Wilma calls (usually pure) virtuals in itself, which are overridden by Fred. This would be much harder to do with composition. class Wilma { protected: void fredCallsWilma() { cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); } virtual void wilmaCallsFred() = 0; }; class Fred : private Wilma { public: void barney() { cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); } protected: virtual void wilmaCallsFred() { cout << "Fred::wilmaCallsFred()\n"; } }; ============================================================================== [22.4] Should I pointer-cast from a private derived class to its base class? Generally, No. From a member function or friend of a privately derived class, the relationship to the base class is known, and the upward conversion from PrivatelyDer* to Base* (or PrivatelyDer& to Base&) is safe; no cast is needed or recommended. However users of PrivateDer should avoid this unsafe conversion, since it is based on a private decision of PrivateDer, and is subject to change without notice. ============================================================================== [22.5] How is protected inheritance related to private inheritance? Similarities: both allow overriding virtuals in the private/protected base class, neither claims the derived is a kind-of its base. Dissimilarities: protected inheritance allows derived classes of derived classes to know about the inheritance relationship. Thus your grand kids are effectively exposed to your implementation details. This has both benefits (it allows subclasses of the protected derived class to exploit the relationship to the protected base class) and costs (the protected derived class can't change the relationship without potentially breaking further derived classes). Protected inheritance uses the : protected syntax: class Car : protected Engine { public: // ... }; ============================================================================== [22.6] What are the access rules with private and protected inheritance? Take these classes as examples: class B { /*...*/ }; class D_priv : private B { /*...*/ }; class D_prot : protected B { /*...*/ }; class D_publ : public B { /*...*/ }; class UserClass { B b; /*...*/ }; None of the subclasses can access anything that is private in B. In D_priv, the public and protected parts of B are private. In D_prot, the public and protected parts of B are protected. In D_publ, the public parts of B are public and the protected parts of B are protected (D_publ is-a-kind-of-a B). class UserClass can access only the public parts of B, which "seals off" UserClass from B. To make a public member of B so it is public in D_priv or D_prot, state the name of the member with a B:: prefix. E.g., to make member B::f(int,float) public in D_prot, you would say: class D_prot : protected B { public: B::f; // Note: Not B::f(int,float) }; ============================================================================== SECTION [23]: Abstraction [23.1] What's the big deal of separating interface from implementation? Interfaces are a company's most valuable resources. Designing an interface takes longer than whipping together a concrete class which fulfills that interface. Furthermore interfaces require the time of more expensive people. Since interfaces are so valuable, they should be protected from being tarnished by data structures and other implementation artifacts. Thus you should separate interface from implementation. ============================================================================== [23.2] How do I separate interface from implementation in C++ (like Modula-2)? Use an ABC (see next FAQ). ============================================================================== [23.3] What is an ABC? An abstract base class. At the design level, an abstract base class (ABC) corresponds to an abstract concept. If you asked a mechanic if he repaired vehicles, he'd probably wonder what kind-of vehicle you had in mind. Chances are he doesn't repair space shuttles, ocean liners, bicycles, or nuclear submarines. The problem is that the term "vehicle" is an abstract concept (e.g., you can't build a "vehicle" unless you know what kind of vehicle to build). In C++, class Vehicle would be an ABC, with Bicycle, SpaceShuttle, etc, being subclasses (an OceanLiner is-a-kind-of-a Vehicle). In real-world OO, ABCs show up all over the place. As programming language level, an ABC is a class that has one or more pure virtual member functions (see next FAQ). You cannot make an object (instance) of an ABC. ============================================================================== [23.4] What is a "pure virtual" member function? A member function declaration that turns a normal class into an abstract class (i.e., an ABC). You normally only implement it a derived class. Some member functions exist in concept; they don't have any reasonable definition. E.g., suppose I asked you to draw a Shape at location (x,y) that has size 7. You'd ask me "what kind of shape should I draw?" (circles, squares, hexagons, etc, are drawn differently). In C++, we must indicate the existence of the draw() member function (so users can call it when they have a Shape* or a Shape&), but we recognize it can (logically) be defined only in subclasses: class Shape { public: virtual void draw() const = 0; // = 0 means it is "pure virtual" // ... }; This pure virtual function makes Shape an ABC. If you want, you can think of the "= 0;" syntax as if the code were at the NULL pointer. Thus Shape promises a service to its users, yet Shape isn't able to provide any code to fulfill that promise. This ensures any actual object created from a [concrete] class derived from Shape will have the indicated member function, even though the base class doesn't have enough information to actually define it yet. Note that it is possible to provide a definition for a pure virtual function, but this usually confuses novices and is best avoided until later. ============================================================================== [23.5] How can I provide printing for an entire hierarchy of classes? Provide a friend operator<< that calls a protected virtual function: class Base { public: friend ostream& operator<< (ostream& o, const Base& b); // ... protected: virtual void print(ostream& o) const; // Or "= 0;" if Base is an ABC }; inline ostream& operator<< (ostream& o, const Base& b) { b.print(o); return o; } class Derived : public Base { protected: virtual void print(ostream& o) const; }; Now all subclasses of Base merely provide their own print(ostream&) const member function (they all share the common operator<<). This technique allows friends to act as if they supported dynamic binding. ============================================================================== [23.6] When should my destructor be virtual? When you may delete a derived object via a base pointer. virtual functions bind to the code associated with the class of the object, rather than with the class of the pointer/reference. When you say delete basePtr, and the base class has a virtual destructor, the destructor that gets invoked is the one associated with the type of the object *basePtr, rather than the one associated with the type of the pointer. This is generally A Good Thing. To make life easy for you, the only time you wouldn't want to make a class's destructor virtual is if that class has no virtual functions, since the introduction of the first virtual function usually imposes some space overhead in each object to implement the magic of dynamic binding. It usually boils down to an extra pointer per object called the "virtual table pointer" or vptr. ============================================================================== [23.7] What is a "virtual constructor"? An idiom that allows you to do something that C++ doesn't directly support. You can get the effect of a virtual constructor by a virtual clone() member function (for copy constructing), or a virtual create() member function (for the default constructor). class Shape { public: virtual ~Shape() { } // See on "virtual destructors" for more virtual void draw() = 0; virtual void move() = 0; // ... virtual Shape* clone() const = 0; // Uses the copy ctor virtual Shape* create() const = 0; // Uses the default ctor }; class Circle : public Shape { public: Circle* clone() const { return new Circle(*this); } Circle* create() const { return new Circle(); } // ... }; In the clone() member function, the new Circle(*this) code calls Circle's copy constructor to copy the state of this into the newly created Circle object. In the create() member function, the new Circle() code calls Circle's default constructor. Users use these as if they were "virtual constructors": void userCode(Shape& s) { Shape* s2 = s.clone(); Shape* s3 = s.create(); // ... delete s2; // Relies on destructor being virtual ! delete s3; // Ditto } This function will work correctly regardless of whether the Shape is a Circle, Square, or some other kind-of Shape that doesn't even exist yet. ============================================================================== SECTION [24]: Style guidelines [24.1] What are some good C++ coding standards? Thank you for reading this answer rather than just trying to set your own coding standards. But beware that some people on comp.lang.c++ are very sensitive on this issue. Nearly every software engineer has, at some point, been exploited by someone who used coding standards as a "power play." Furthermore some attempts to set C++ coding standards have been made by those who didn't know what they were talking about, so the standards end up being based on what was the state-of-the-art when the standards setters where writing code. Such impositions generate an attitude of mistrust for coding standards. Obviously anyone who asks this question wants to be trained so they don't run off on their own ignorance, but nonetheless posting a question such as this one to comp.lang.c++ tends to generate more heat than light. ============================================================================== [24.2] Are coding standards necessary? Are they sufficient? Coding standards do not make non-OO programmers into OO programmers; only training and experience do that. If coding standards have merit, it is that they discourage the petty fragmentation that occurs when large organizations coordinate the activities of diverse groups of programmers. But you really want more than a coding standard. The structure provided by coding standards gives neophytes one less degree of freedom to worry about, which is good. However pragmatic guidelines should go well beyond pretty-printing standards. Organizations need a consistent philosophy of design and implementation. E.g., strong or weak typing? references or pointers in interfaces? stream I/O or stdio? should C++ code call C code? vice versa? how should ABCs be used? should inheritance be used as an implementation technique or as a specification technique? what testing strategy should be employed? inspection strategy? should interfaces uniformly have a get() and/or set() member function for each data member? should interfaces be designed from the outside-in or the inside-out? should errors be handled by try/catch/throw or by return codes? etc. What is needed is a "pseudo standard" for detailed design. I recommend a three-pronged approach to achieving this standardization: training, mentoring, and libraries. Training provides "intense instruction," mentoring allows OO to be caught rather than just taught, and high quality C++ class libraries provide "long term instruction." There is a thriving commercial market for all three kinds of "training." Advice by organizations who have been through the mill is consistent: Buy, Don't Build. Buy libraries, buy training, buy tools, buy consulting. Companies who have attempted to become a self-taught tool-shop as well as an application/system shop have found success difficult. Few argue that coding standards are "ideal," or even "good," however they are necessary in the kind of organizations/situations described above. The following FAQs provide some basic guidance in conventions and styles. ============================================================================== [24.3] Should our organization determine coding standards from our C experience? No! No matter how vast your C experience, no matter how advanced your C expertise, being a good C programmer does not make you a good C++ programmer. Converting from C to C++ is more than just learning the syntax and semantics of the ++ part of C++. Organizations who want the promise of OO, but who fail to put the "OO" into "OO programming", are fooling themselves; the balance sheet will show their folly. C++ coding standards should be tempered by C++ experts. Asking comp.lang.c++ is a start. Seek out experts who can help guide you away from pitfalls. Get training. Buy libraries and see if "good" libraries pass your coding standards. Do not set standards by yourself unless you have considerable experience in C++. Having no standard is better than having a bad standard, since improper "official" positions "harden" bad brain traces. There is a thriving market for both C++ training and libraries from which to pool expertise. One more thing: whenever something is in demand, the potential for charlatans increases. Look before you leap. Also ask for student-reviews from past companies, since not even expertise makes someone a good communicator. Finally, select a practitioner who can teach, not a full time teacher who has a passing knowledge of the language/paradigm. ============================================================================== [24.4] Should I declare locals in the middle of a function or at the top? Declare near first use. An object is initialized (constructed) the moment it is declared. If you don't have enough information to initialize an object until half way down the function, you should create it half way down the function when it can be initialized correctly. Don't initialize it to an "empty" value at the top then "assign" it later. The reason for this is runtime performance. Building an object correctly is faster than building it incorrectly and remodeling it later. Simple examples show a factor of 350% speed hit for simple classes like String. Your mileage may vary; surely the overall system degradation will be less that 350%, but there will be degradation. Unnecessary degradation. A common retort to the above is: "we'll provide set() member functions for every datum in our objects so the cost of construction will be spread out." This is worse than the performance overhead, since now you're introducing a maintenance nightmare. Providing a set() member function for every datum is tantamount to public data: you've exposed your implementation technique to the world. The only thing you've hidden is the physical names of your member objects, but the fact that you're using a List and a String and a float, for example, is open for all to see. Bottom line: Locals should be declared near their first use. Sorry that this isn't familiar to C experts, but new doesn't necessarily mean bad. ============================================================================== [24.5] What source-file-name convention is best? foo.cpp? foo.C? foo.cc? If you already have a convention, use it. If not, consult your compiler to see what the compiler expects. Typical answers are: .C, .cc, .cpp, or .cxx (naturally the .C extension assumes a case-sensitive file system to distinguish .C from .c). At Paradigm Shift, Inc., we have used both .cpp for our C++ source files, and we have also used .C. In the latter case, we supply the compiler option forces .c files to be treated